import axios from 'axios'
import qs from 'qs'
import config from '@/config'
import { Message } from 'element-ui'

let baseUrl = ''
switch (process.env.NODE_ENV) {
  case 'development':
    // 这里是本地的请求url
    baseUrl = config.apiUrl.dev
    break
  case 'production':
    // 生产环境url
    baseUrl = config.apiUrl.pro
    break
}

/**
 * 创建axios实例
 * @type {AxiosInstance}
 */
const service = axios.create({
  // api的base_url
  baseURL: baseUrl,
  // 设置请求超时时间30s
  timeout: 60000
})

/**
 * 请求参数处理
 */
service.interceptors.request.use((config) => {
    console.log('url:' + config.url + ',method:' + config.method);

    const contentType = config.headers['Content-Type'];
    if (contentType && contentType == 'multipart/form-data') {

    } else {
      config.method === 'post'
        ? config.data = qs.stringify({...config.data})
        : config.params = {...config.data}
    }
    return config
  }
)

/**
 * 响应结果处理
 */
service.interceptors.response.use(
  (response) => {
    if (response.data.code === 200) {
      return Promise.resolve(response.data)
    } else {
      Message.error({content: response.data.message})
      return Promise.reject(response.data)
    }
  }, error => {
    let message = ''
    message = '连接服务器失败'
    Message.error({content: message})
    return Promise.reject(error)
  }
)

export default service
